<!-- 菜单树组件 -->
<template>
  <el-tree
    ref="treeRef"
    :data="treeData"
    :props="defaultProps"
    show-checkbox
    node-key="menuindex"
    highlight-current
    :default-checked-keys="checkedKeys"
    @check-change="handleCheckChange"
    default-expand-all
  />
 
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted } from 'vue';
import { getMenuTree } from '../utils/menu';
import { ElTree } from 'element-plus'; // 引入 ElTree 类型定义


export default defineComponent({
  name: 'MenuTree',
  props: {
    rolePermissions: {
      type: Array as () => string[],
      default: () => []
    }
  },
  setup(props, { emit }) {
    // const treeRef = ref(null);
    const treeRef = ref<InstanceType<typeof ElTree> | null>(null); // 明确 treeRef 的类型
    const treeData = ref<any[]>([]);
    const defaultProps = ref({
      children: 'children',
      label: 'label'
    });
    const checkedKeys = ref<string[]>([]);

    onMounted(async () => {
      treeData.value = await getMenuTree();
      updateCheckedKeys();
    });

    // 监听权限变化并更新勾选状态
    watch(() => props.rolePermissions, (newPermissions) => {
      debugger;
      checkedKeys.value = newPermissions;
      updateCheckedKeys();
    });

    // 更新勾选状态
    const updateCheckedKeys = () => {
      debugger;
      if (treeRef.value) {
        treeRef.value.setCheckedKeys(checkedKeys.value);
      }
    };

    // 处理勾选变化
    const handleCheckChange = () => {
      debugger;
      if (treeRef.value) {
      const checkedKeys = treeRef.value.getCheckedKeys();
      const fullyCheckedKeys = treeRef.value.getCheckedKeys(); // 完全选中的节点
      const halfCheckedKeys = treeRef.value.getHalfCheckedKeys(); // 部分选中的节点
      const checkedKeyss = [...fullyCheckedKeys, ...halfCheckedKeys]; // 合并结果
      emit('update:rolePermissions', checkedKeys,checkedKeyss);
      }
    };
    return {
      treeRef,
      treeData,
      defaultProps,
      checkedKeys,
      handleCheckChange
    };
  }
});
</script>